package com.bff.gaia.mix.api.xjoin2.core.utils;

import com.bff.gaia.shaded.guava18.com.google.common.base.Strings;
import com.bff.gaia.shaded.guava18.com.google.common.collect.Maps;

import java.util.Map;

public class StringUtil {
	/**
	 * add specify params to dbUrl
	 * @param dbUrl
	 * @param addParams
	 * @param isForce true:replace exists param
	 * @return
	 */
	public static String addJdbcParam(String dbUrl, Map<String, String> addParams, boolean isForce){

		if(Strings.isNullOrEmpty(dbUrl)){
			throw new RuntimeException("dburl can't be empty string, please check it.");
		}

		if(addParams == null || addParams.size() == 0){
			return dbUrl;
		}

		String[] splits = dbUrl.split("\\?");
		String preStr = splits[0];
		Map<String, String> params = Maps.newHashMap();
		if(splits.length > 1){
			String existsParamStr = splits[1];
			String[] existsParams = existsParamStr.split("&");
			for(String oneParam : existsParams){
				String[] kv = oneParam.split("=");
				if(kv.length != 2){
					throw new RuntimeException("illegal dbUrl:" + dbUrl);
				}

				params.put(kv[0], kv[1]);
			}
		}

		for(Map.Entry<String, String> addParam : addParams.entrySet()){
			if(!isForce && params.containsKey(addParam.getKey())){
				continue;
			}

			params.put(addParam.getKey(), addParam.getValue());
		}

		//rebuild dbURL
		StringBuilder sb = new StringBuilder();
		boolean isFirst = true;
		for(Map.Entry<String, String> param : params.entrySet()){
			if(!isFirst){
				sb.append("&");
			}

			sb.append(param.getKey()).append("=").append(param.getValue());
			isFirst = false;
		}

		return preStr + "?" + sb.toString();
	}
}